(function () {
  'use strict';

  angular
    .module('client')
    .controller('DeviceController', DeviceController);

  DeviceController.$inject = ['$scope', '$interval', '$state', '$uibModal', 'deviceService', 'POOL_TIME'];
  function DeviceController($scope, $interval, $state, $uibModal, deviceService, POOL_TIME) {
    var vm = this;
    vm.devices = [];
    vm.apply = apply;
    vm.round = deviceService.round;
    $scope.$on('$destroy', function () {
      stopPoll(poll);
    });

    var poll = undefined;
    function stopPoll(poll) {
      if (angular.isDefined(poll)) {
        $interval.cancel(poll);
        poll = undefined;
      }
    }

    function initApplyModal(opts) {
      var modal = $uibModal.open({
        templateUrl: 'app/device/apply/apply.html',
        controller: 'ApplyController',
        controllerAs: 'vm',
        size: 'md',
        resolve: {
          deviceInfo: opts
        }
      });

      modal.result.then(function (deviceInfo) {
        stopPoll(poll);
        deviceService.setDeviceSize(deviceInfo.width, deviceInfo.height);
        $state.go('control', {
          deviceID: deviceInfo.deviceID,
        });
      }, function () {

      });
    }

    function apply(opts) {
      deviceService.isAllowApply()
        .then(function (resp) {
          if (resp.data.isAllow) {
            initApplyModal(opts);
          } else {
            swal({
              title: "最多同时使用一台设备",
              text: resp.msg,
              type: "warning",
              timer: 3000,
              showCancelButton: false,
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "确定",
            });
          }
        })
    }

    // init when page load
    // TODO: 在视图展示之前通过 resolve 解决依赖
    poll = $interval(function () {
      deviceService
        .getDeviceInfo()
        .then(function (resp) {
          vm.devices = resp.data;
        });
    }, POOL_TIME);

    deviceService
      .getDeviceInfo()
      .then(function (resp) {
        vm.devices = resp.data;
      });

  }
})();
